package com.fas.core.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONObject;

import com.jfinal.plugin.activerecord.Model;

public class ModelUtil {

	/**
	 * 将json对象转换成Map
	 * 
	 * @param jsonmap
	 * @return
	 * @author: Jerri Liu
	 * @date: 2014年3月30日下午5:17:33
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> jsonToMap(net.sf.json.JSONObject jsonmap) {
		Map<String, Object> map = new HashMap<String, Object>();
		Iterator<String> iterator = (Iterator<String>) jsonmap.keys();
		String key = null;
		Object value = null;
		while (iterator.hasNext()) {
			key = iterator.next();
			try {
				value = jsonmap.get(key);
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put(key, value);
		}
		return map;
	}
	
	public static Model<?>  jsonToModel(String jsonStr,Class<?> modelClass){
		Model<?> model = null;
		try {
			model =  (Model<?>) modelClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		JSONObject jsonObj = JSONObject.fromObject(jsonStr);
		Map<String, Object>  map = jsonToMap(jsonObj);
		model.setAttrs(map);
		return model;
	}
}
